<script setup lang="ts">
import { ref } from 'vue'
import markdownEditor from '../../components/markdownEditor.vue'
import useArticel from '../../composition/useArticel'
import { useRouter, useRoute } from 'vue-router'
import { useArticleStore } from '../../store/articel'
import { showToast } from 'vant'

const router = useRouter()
const route = useRoute()

const { getCategoryList, categoryList, getOneArticle, articel } = useArticel()
const articleStore = useArticleStore()
const form = ref(articleStore.articel)
await getCategoryList()

const preView = () => {
   if (!form.value?.content) return showToast('文章内容不能为空')
   if (!form.value?.categoryId) return showToast('请选择分类')
   if (!form.value.title) return showToast('标题不能为空')
   router.push({ name: 'preDetail' })
}

if (route.query.id) {
   await getOneArticle(+route.query.id)
   form.value.title = articel.value!.title
   form.value.content = articel.value!.content
   form.value.previewImg = articel.value!.previewImg
   form.value.categoryId = articel.value!.categoryId
}

const plain = ref(0)
const selectCategory = (item: { id: number; name: string }) => {
   form.value!.categoryId = item.id
   plain.value = item.id
}
</script>

<template>
   <div>
      <div class="mb-2">
         <van-nav-bar
            title="编辑文章"
            left-text="主页"
            right-text="预览"
            left-arrow
            @click-left="$router.push({ name: 'home' })"
            @click-right="preView" />
      </div>

      <div class="categories flex justify-start items-center gap-2 p-4">
         <template v-for="item in categoryList?.data">
            <van-tag
               v-if="item.id != 1"
               :plain="plain != item.id"
               type="primary"
               size="medium"
               @click="selectCategory(item)"
               >{{ item.name }}</van-tag
            >
         </template>
      </div>

      <van-field label="标题" placeholder="请输入标题" v-model="form!.title" />
      <markdownEditor v-model:content="form!.content" />
   </div>
</template>

<style scoped lang="scss">
::v-deep .van-field__label {
   width: 50px;
   font-weight: 500;
   margin-bottom: 10px;
}
</style>
